package com.wuseguang.springcloud.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import static org.apache.poi.util.LittleEndian.getShort;

/**
 * @描述 发送请求的get post 请求
 * @创建人 zm
 * @创建时间 2019/11/17
 */
public class HttpRequestUtil {

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String Get(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String Post(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("Authorization", param);

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param, Map<String, String> paramMap) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setDoOutput(true);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            OutputStream os = connection.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            osw.write(JSON.toJSONString(paramMap));
            osw.flush();
            osw.close();
            os.close();

            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    //post请求方法
    public static String sendPost(String url, Map<String, Object> params) {
        String response = null;
        System.out.println(url);
        System.out.println(params);
        try {
            List<NameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<NameValuePair>(params.size());
                for (String key : params.keySet()) {
                    pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
            }
            CloseableHttpClient httpclient = null;
            CloseableHttpResponse httpresponse = null;
            try {
                httpclient = HttpClients.createDefault();
                HttpPost httppost = new HttpPost(url);
                // StringEntity stringentity = new StringEntity(data);
                if (pairs != null && pairs.size() > 0) {
                    httppost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
                }
                httpresponse = httpclient.execute(httppost);
                response = EntityUtils
                        .toString(httpresponse.getEntity());
                System.out.println(response);
            } finally {
                if (httpclient != null) {
                    httpclient.close();
                }
                if (httpresponse != null) {
                    httpresponse.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * https://m.aliyun.com/yunqi/articles/544596?spm=5176.11156470.0.0.f35a5824tYP7NZ&from=singlemessage&isappinstalled=0
     *
     * @描述 获取天气精简版  可以参考以上链接
     * @创建人 zm
     * @创建时间 2020/2/14
     */
    public static String getWeatherInfo(String url, String citykey) {
        CloseableHttpClient client;
        client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url + citykey);
        HttpResponse response;
        try {
            response = client.execute(get);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instreams = entity.getContent();
                String str = convertStreamToString(instreams);
                get.abort();
                return str;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String convertStreamToString(InputStream is) {
        StringBuilder sb1 = new StringBuilder();
        byte[] bytes = new byte[4096];
        int size;
        try {
            while ((size = is.read(bytes)) > 0) {
                String str = new String(bytes, 0, size, "UTF-8");
                sb1.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb1.toString();
    }

    /**
     * 发送图片请求发post
     * @param url 发送的地址
     * @param multipartFile 发送的图片
     * @return
     * @throws IOException
     */
    public static String postPic(String url, MultipartFile multipartFile) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        CloseableHttpResponse response = null;

        HttpPost request = new HttpPost(url );
        request.addHeader("Content-Type", "application/octet-stream");

        InputStream inputStream = multipartFile.getInputStream();

        byte[] byt = new byte[inputStream.available()];
        inputStream.read(byt);
        request.setEntity(new ByteArrayEntity(byt, ContentType.create(multipartFile.getContentType())));

        response = httpclient.execute(request);
        HttpEntity httpEntity = response.getEntity();
        String result = EntityUtils.toString(httpEntity, "UTF-8");// 转成string
        return  result;
    }


    /**
     * 向指定URL发送GET方法的请求 带token （海威达）
     * @param url
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param token 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return
     */
    public static String GetTwo(String url, String param,String token) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url ;
            URL realUrl = new URL(urlNameString);
            //忽略HTTPS请求的SSL证书，必须在openConnection之前调用
            SslUtils.ignoreSsl();
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Authorization",token);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }



    /**
     * 向指定 URL 发送POST方法的请求（海威达）
     *
     * @param url   发送请求的 URL
     * @param bodyData 请求参数
     * @param token  token
     * @return 所代表远程资源的响应结果
     */
    public static String sendPostToken(String url, String bodyData,String  token) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            //忽略HTTPS请求的SSL证书，必须在openConnection之前调用
            SslUtils.ignoreSsl();
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("Authorization", token);

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            out.write(bodyData);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] args) {
     /*   String url = "https://hwdedu.mzapi.com:8077/apij/login";
        String result =  sendPostToken(url, "{\n" +
                "    \"schoolCode\":\"20200709\",\n" +
                "    \"userName\":\"15016214503\",\n" +
                "    \"passWord\":\"123456\",\n" +
                "    \"uuid\":\"123456\"\n" +
                "}","");*/


      /*String url = "https://hwdedu.mzapi.com:8077/apij/access/RefreshToken?uuid=0efc1dee-5091-40f3-8e05-d9cce067bd09";
        String result =  sendPostToken(url, "","JWT eyJhbGciOiJIUzUxMiJ9.eyJyYW5kb21LZXkiOiI1Z25ncXkiLCJzdWIiOiJ7XCJkcHRTeXNJZFwiOlwiNDM4NmM3YzAtYzE4Yy0xMWVhLThhOTAtMDI0MmFjMTEwMDBiXCIsXCJlbXBTeXNJZFwiOlwiNDM4YTUyOWUtYzE4Yy0xMWVhLWFhNDEtMDI0MmFjMTEwMDBiXCIsXCJlbXBuYW1lXCI6XCLotbXmlY_ogapcIixcImVtcG5vXCI6XCIxNTAxNjIxNDUwM1wiLFwiaWRib3VuZFwiOmZhbHNlLFwiam9iTm9cIjpcIjE1MDE2MjE0NTAzXCIsXCJzY2hvb2xDb2RlXCI6XCIyMDIwMDcwOVwiLFwic3R1ZGVudE5vXCI6XCIxNTAxNjIxNDUwM1wiLFwidGVuYW50Q29kZVwiOlwiMjAyMDA0MTRcIixcInVzZXJJZFwiOlwiNDM4ZTI5MDItYzE4Yy0xMWVhLWI2ZDEtMDI0MmFjMTEwMDBiXCIsXCJ1c2VyTmFtZVwiOlwiMTUwMTYyMTQ1MDNcIixcInVzZXJUeXBlXCI6XCJzY2hvb2xfbWFuYWdlclwifSIsImV4cCI6MTU5NTk1NzE0MSwiaWF0IjoxNTk1OTI2MTc5fQ.2FqLwrmq-D0KPVzFswp2RqUDroQTwueXppEq0Nw2EJPWgJWidYQ89sdaaTux7qURB0a8wlQOqnE4SmWUxx857w");*/


        String result = HttpRequestUtil.GetTwo( "https://hwdedu.mzapi.com:8077/apij/api/open/notice/gate/get?minute=5", "", "JWT eyJhbGciOiJIUzUxMiJ9.eyJyYW5kb21LZXkiOiJzMjhybmwiLCJzdWIiOiJ7XCJkcHRTeXNJZFwiOlwiNDM4NmM3YzAtYzE4Yy0xMWVhLThhOTAtMDI0MmFjMTEwMDBiXCIsXCJlbXBTeXNJZFwiOlwiNDM4YTUyOWUtYzE4Yy0xMWVhLWFhNDEtMDI0MmFjMTEwMDBiXCIsXCJlbXBuYW1lXCI6XCLotbXmlY_ogapcIixcImVtcG5vXCI6XCIxNTAxNjIxNDUwM1wiLFwiaWRib3VuZFwiOmZhbHNlLFwiam9iTm9cIjpcIjE1MDE2MjE0NTAzXCIsXCJzY2hvb2xDb2RlXCI6XCIyMDIwMDcwOVwiLFwic3R1ZGVudE5vXCI6XCIxNTAxNjIxNDUwM1wiLFwidGVuYW50Q29kZVwiOlwiMjAyMDA0MTRcIixcInVzZXJJZFwiOlwiNDM4ZTI5MDItYzE4Yy0xMWVhLWI2ZDEtMDI0MmFjMTEwMDBiXCIsXCJ1c2VyTmFtZVwiOlwiMTUwMTYyMTQ1MDNcIixcInVzZXJUeXBlXCI6XCJzY2hvb2xfbWFuYWdlclwifSIsImV4cCI6MTU5NTk2MDIyMCwiaWF0IjoxNTk1OTI2MzYzfQ.Pkj03SygAcvzllu_uQi5JIm6zHOjWJYr91gzdN6h35k8J4UsZpwEV-0DuDPN0COiKlQTCCSuwoc7_IP5jRI_0w");
      System.err.println(result);
    }



}